//
//  CarInfoController.swift
//  TrafficViolation
//
//  Created by clover on 2017/4/22.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class CarInfoController: BaseController {
    let leftX = CGFloat(10)
    var car:CarModel!
    var carlicense,enginenum,remark,phone:UITextField!
    var carnum,verify : UILabel!
    var violationArray: [ViolationModel] = Array<ViolationModel>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        setupNavBar(title: "车辆信息", isback: true, appearWay: 2, isright: false)//自定义导航
        let carnumView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 0), width: kScreenW, height: cellH))
        let carnum_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        carnum_left.text = "车牌号码"
        carnum_left.font = UIFont.systemFont(ofSize: 14)
        carnumView.addSubview(carnum_left)
        carnum = UILabel(frame: CGRect(x: 80, y: 0, width: kScreenW - 115, height: cellH))
        carnum.textColor = UIColor.darkGray
        carnum.font = UIFont.systemFont(ofSize: 14)
        carnum.text = car.carnum
        carnumView.addSubview(carnum)
        self.view.addSubview(carnumView)
        //细分割线
        self.view.addSubview(getSeparator(index: 1))
        
        let carlicenseView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 1), width: kScreenW, height: cellH))
        let carlicense_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        carlicense_left.text = "车身架号"
        carlicense_left.font = UIFont.systemFont(ofSize: 14)
        carlicenseView.addSubview(carlicense_left)
        carlicense = UITextField(frame: CGRect(x: 80, y: 0, width: kScreenW - 115, height: cellH))
        carlicense.placeholder = "请输入车身架号"
        carlicense.font = UIFont.systemFont(ofSize: 14)
        carlicense.text = car.carlicense
        carlicenseView.addSubview(carlicense)
        self.view.addSubview(carlicenseView)
        let btn1 = UIButton(frame:CGRect(x:kScreenW - 40, y: (cellH - CGFloat(15)) / 2, width: 15, height: 15))
        btn1.tag = 1
        btn1.setBackgroundImage(UIImage(named:"wenhao"), for: .normal)
        btn1.addTarget(self, action: #selector(showClick(sender:)), for: UIControlEvents.touchUpInside)
        carlicenseView.addSubview(btn1)
        //细分割线
        self.view.addSubview(getSeparator(index: 2))
        
        let enginenumView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 2), width: kScreenW, height: cellH))
        let enginenum_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        enginenum_left.text = "发动机号"
        enginenum_left.font = UIFont.systemFont(ofSize: 14)
        enginenumView.addSubview(enginenum_left)
        enginenum = UITextField(frame: CGRect(x: 80, y: 0, width: kScreenW - 115, height: cellH))
        enginenum.placeholder = "请输入发动机号"
        enginenum.font = UIFont.systemFont(ofSize: 14)
        enginenum.text = car.enginenum
        enginenumView.addSubview(enginenum)
        self.view.addSubview(enginenumView)
        let btn2 = UIButton(frame:CGRect(x:kScreenW - 40, y: (cellH - CGFloat(15)) / 2, width: 15, height: 15))
        btn2.tag = 2
        btn2.setBackgroundImage(UIImage(named:"wenhao"), for: .normal)
        btn2.addTarget(self, action: #selector(showClick(sender:)), for: UIControlEvents.touchUpInside)
        enginenumView.addSubview(btn2)
        //细分割线
        self.view.addSubview(getSeparator(index: 3))
        
        let remarkView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 3), width: kScreenW - 20, height: cellH))
        let remark_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        remark_left.text = "备注信息"
        remark_left.font = UIFont.systemFont(ofSize: 14)
        remarkView.addSubview(remark_left)
        remark = UITextField(frame: CGRect(x: 80, y: 0, width: kScreenW - 100, height: cellH))
        remark.placeholder = "如张三的车(选填)"
        remark.font = UIFont.systemFont(ofSize: 14)
        remark.text = car.remark
        remarkView.addSubview(remark)
        self.view.addSubview(remarkView)
        //细分割线
        self.view.addSubview(getSeparator(index: 4))
        
        let phoneView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 4), width: kScreenW - 20, height: cellH))
        let phone_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        phone_left.text = "手机号码"
        phone_left.font = UIFont.systemFont(ofSize: 14)
        phoneView.addSubview(phone_left)
        phone = UITextField(frame: CGRect(x: 80, y: 0, width: kScreenW - 100, height: cellH))
        phone.placeholder = "请输入手机号码"
        phone.font = UIFont.systemFont(ofSize: 14)
        phone.text = car.phoneNum
        phoneView.addSubview(phone)
        self.view.addSubview(phoneView)
        //细分割线
        self.view.addSubview(getSeparator(index: 5))
        
        let noticeView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 5), width: kScreenW - 20, height: cellH))
        let notice_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        notice_left.text = "* 注  意 :"
        notice_left.textColor = UIColor.red
        notice_left.font = UIFont.systemFont(ofSize: 14)
        noticeView.addSubview(notice_left)
        let notieLabel = UILabel(frame: CGRect(x: 80, y: 0, width: kScreenW - 100, height: cellH))
        notieLabel.font = UIFont.systemFont(ofSize: 11)
        notieLabel.textColor = UIColor(red: 195/255, green: 195/255, blue: 201/255, alpha: 1)
        notieLabel.numberOfLines = 3
        notieLabel.textAlignment=NSTextAlignment.left
        notieLabel.text = "浙江牌照必须输入手机号码以便查询违章信息，一个手机号码只能查询三辆车，一辆车只能绑定三个手机号码"
        noticeView.addSubview(notieLabel)
        self.view.addSubview(noticeView)
        //细分割线
        self.view.addSubview(getSeparator(index: 6))
        
        let verifyView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 6), width: kScreenW - 20, height: cellH))
        let verify_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        verify_left.text = "车辆验证"
        verify_left.font = UIFont.systemFont(ofSize: 14)
        verifyView.addSubview(verify_left)
        verify = UILabel.init(frame: CGRect(x: kScreenW - 110, y: 0, width: 60, height: cellH))
        verify.textAlignment = .right
        verify.font = UIFont.systemFont(ofSize: 14)
        if car.carStatus == "0" {
            verify.text = "待认证"
            verify.textColor = UIColor.red
        }
        if car.carStatus == "1" {
            verify.text = "认证成功"
            verify.textColor = appMainColor
        }
        verifyView.addSubview(verify)
        self.view.addSubview(verifyView)
        //细分割线
        self.view.addSubview(getSeparator(index: 7))
        
        let onwerView = UIView.init(frame: CGRect(x: 0, y: getCellY(index: 7), width: kScreenW - 20, height: cellH))
        let onwer_left = UILabel(frame: CGRect(x: leftX, y: 0, width: 60, height: cellH))
        onwer_left.text = "车主资料"
        onwer_left.font = UIFont.systemFont(ofSize: 14)
        onwerView.addSubview(onwer_left)
        let onwer = UIButton.init(frame: CGRect(x: kScreenW - 150, y: 0, width: 110, height: cellH))
        onwer.setTitle("点击添加/修改", for: .normal)
        onwer.setTitleColor(appMainColor, for: .normal)
        onwer.titleLabel?.textAlignment = .right
        onwer.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        onwer.addTarget(self, action: #selector(verifyCarClick(sender:)), for: UIControlEvents.touchUpInside)
        onwerView.addSubview(onwer)
        self.view.addSubview(onwerView)
        let btn3 = UIButton(frame:CGRect(x:kScreenW - 40, y: (cellH - CGFloat(20)) / 2, width: 20, height:20))
        btn3.tag = 3
        btn3.setBackgroundImage(UIImage(named:"icon_right"), for: .normal)
        btn3.addTarget(self, action: #selector(verifyCarClick(sender:)), for: UIControlEvents.touchUpInside)
        onwerView.addSubview(btn3)
        //细分割线
        self.view.addSubview(getSeparator(index: 8))
        
        //详情介绍
        let detailLabel = UILabel(frame: CGRect(x: 40, y: getCellY(index: 8), width: kScreenW - 80, height: cellH))
        detailLabel.font = UIFont.systemFont(ofSize: 10)
        detailLabel.textColor = UIColor(red: 195/255, green: 195/255, blue: 201/255, alpha: 1)
        detailLabel.numberOfLines = 2
        detailLabel.textAlignment=NSTextAlignment.center
        detailLabel.text = "所填信息为当地交管局查询所需，您的车辆信息我们将严格保密，请放心填写"
        self.view.addSubview(detailLabel)
        
        let savebtn = UIButton(frame:CGRect(x: 20, y: getCellY(index: 9), width: kScreenW - 40, height: 40))
        savebtn.setTitle("保存并查询", for: .normal)
        savebtn.backgroundColor = appMainColor
        savebtn.showsTouchWhenHighlighted = true
        savebtn.layer.cornerRadius = 10;
        savebtn.addTarget(self, action: #selector(updateCarClick), for: .touchUpInside)
        self.view.addSubview(savebtn)
        
        let deletebtn = UIButton(frame:CGRect(x: 20, y: getCellY(index: 10)+10, width: kScreenW - 40, height: 40))
        deletebtn.setTitle("删除", for: .normal)
        deletebtn.backgroundColor = UIColor.red
        deletebtn.showsTouchWhenHighlighted = true
        deletebtn.layer.cornerRadius = 10;
        deletebtn.addTarget(self, action: #selector(deletebtnClick), for: .touchUpInside)
        self.view.addSubview(deletebtn)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
extension CarInfoController {
    func getCellY(index : Int) -> CGFloat {
        return cellH * CGFloat(index) + kStatusBarH + kNavigationBarH
    }
    
    func getSeparator(index: Int) -> UILabel {
        let lab = UILabel.init(frame: CGRect(x: leftX, y: getCellY(index: index), width: kScreenW - 20, height: 1))
        lab.backgroundColor = separatorColor
        return lab
    }
    //问号，点击查看车架号和发动机号
    func showClick(sender: UIButton){
        let img:UIImage!
        if(1 == sender.tag){
            img = UIImage(named: "carcode_img")
        }else{
            img = UIImage(named: "carengine_img")
        }
        let notice = LoadingView()
        notice.loadingPic(image: img)
    }
    //添加和修改车辆认证信息
    func verifyCarClick(sender: UIButton){
        if reachability.isReachable {
            let verify = VerifyCarController()
            //查询车辆认证信息
            let urlString = "\(projectUrl)/car/carInfo/\(car.carid)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        let model = CarModel.init(dic: json["rdata"])
                        verify.car = model
                        self.present(verify, animated: true, completion: nil)
                    }
                    else{
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print(response.result.error!) //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //删除车辆信息
    func deletebtnClick(){
        if reachability.isReachable {
            let urlString = "\(projectUrl)/car/deleteCar/\(car.carid)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
            Alamofire.request(urlString, method: .post, parameters: nil, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    let alertController = UIAlertController(title: "通知", message: json["rdata"].rawString(), preferredStyle: .alert)
                    if json["success"] == true {
                        let okAction = UIAlertAction(title: "确定", style: .default, handler:{
                            (UIAlertAction) -> Void in
                            self.navigationController?.popViewController(animated: true)
                        })
                        alertController.addAction(okAction)
                        
                    }else{
                        NSLog("删除车辆信息出错啦!\(json["rdata"])")
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                    self.present(alertController, animated: true, completion: nil)
                }
                else{
                    print(response.result.error!) //输出错误日志
                }
            }
 
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //修改车辆信息
    func  updateCarClick() {
        if "" == carlicense.text! {
            checkAlertFun(message: "请输入车架号！")
        }
        else if "" == enginenum.text! {
            checkAlertFun(message: "请输入发动机号！")
        }
        else {
            updateCarFunc()
        }
    }
    //保存车辆信息
    func updateCarFunc(){
        if reachability.isReachable {
            let urlString = "\(projectUrl)/car/updateCar/\(car.carid)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            let params:[String:Any] = [
                "carNum":carnum.text!,
                "carLicense":carlicense.text!,
                "engineNum":enginenum.text!,
                "remark":remark.text!,
                "phoneNum":phone.text!
            ]
            Alamofire.request(urlString, method: .post, parameters: params, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        let vlc = ViolationListController()
                        vlc.carnum = self.carnum.text!
                        vlc.carid = self.car.carid
                        self.navigationController?.present(vlc, animated: true, completion: nil)
                    }
                    else{
                        NSLog("修改车辆信息出错啦!\(json["rdata"])")
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print(response.result.error!) //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
